<template>
  <div style="margin-top:0">
    <!--客户饼图-->
    <div class="data-title">
        <div class="title-left">
           <div class="title-item" :class="{'choose':cutIndex1 == 1}"  @click="changeTab1(1)">供应商贡献</div>
           <div class="title-item" :class="{'choose':cutIndex1 == 2}"  @click="changeTab1(2)">供应商分类</div>
           <div class="title-item" :class="{'choose':cutIndex1 == 3}"  @click="changeTab1(3)">供应商等级</div>
        </div>
        <div class="title-right">
          <el-select @change="getPieData" size="mini" placeholder="请选择毛利统计类型"  style="margin-right: 10px;width:150px" v-model="listQuery1.profitType" >
            <el-option :key="1" value="purchase" label="采购毛利统计"></el-option>
            <el-option :key="2" value="company" label="采销毛利统计"></el-option>
          </el-select>
            <el-date-picker
              @change="getPieData"
              style="width:210px;margin-right: 10px"
              size="mini"
              value-format="yyyy-MM-dd"
              v-model="listQuery1.date"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          <el-select @change="getPieData" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery1.goodsClass" >
            <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
          </el-select>
          <el-input size="mini" v-if="listQuery1.goodsClass" @change="getPieData" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery1.brandName"></el-input>
          <el-select @change="getPieData" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery1.kingGoodsId" filterable>
              <el-option
                v-for="item in goodsList"
                :key="item.kingId"
                :label="item.goodsSn"
                :value="item.kingId">
              </el-option>
          </el-select>
          <el-select size="mini" v-model="listQuery1.userIds"
                     style="width:140px"
                     collapse-tags
                     clearable @change="getPieData"  placeholder="请选择人员" multiple>
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>

        </div>
     </div>
    <div class="order-block">
        <div class="data-block pie-block">
          <div class="pie-menu">
             <div class="pie-menu-item" :class="{'choose':listQuery1.tab == 'shipNum'}" @click="changeItem1('shipNum')">出库量</div>
             <div class="pie-menu-item" :class="{'choose':listQuery1.tab == 'shipProfit'}" @click="changeItem1('shipProfit')">总毛利</div>
             <div class="pie-menu-item" :class="{'choose':listQuery1.tab == 'perShipProfit'}" @click="changeItem1('perShipProfit')">吨毛利</div>
          </div>
          <div id="pieChart" class="charts-div" style="height:406px"></div>

        </div>
        <div class="data-block order-table pie-table">
          <el-table :data="list1"  style="width: 100%;" class="data-table" :height="390" v-loading="listLoading1" v-if="cutIndex1 == 1">
            <el-table-column
              align="center"
              label="供应商名称"
              min-width="300">
              <template slot-scope="scope"><el-link @click="toPage('pSupplierSaleNumAnalysis')">{{scope.row.supplierName}}</el-link></template>
            </el-table-column>
            <el-table-column
              align="center"
              label="出库量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.shipNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="总毛利"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.shipProfit}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="吨毛利"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.perShipProfit}}
              </template>
            </el-table-column>
          </el-table>
          <el-table :data="list1"  style="width: 100%;" class="data-table" v-loading="listLoading1" v-if="cutIndex1 == 2">
            <el-table-column
              align="center"
              label="供应商分类"
              min-width="150">
              <template slot-scope="scope"><el-link @click="toPage('pSupplierSaleNumAnalysis')">{{scope.row.supplierType}}</el-link></template>
            </el-table-column>
            <el-table-column
              align="center"
              label="数量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.supplierCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="占比"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.supplierRate}}%
              </template>
            </el-table-column>

            <el-table-column
              prop="shipNum"
              align="center"
              label="出库量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.shipNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="shipProfit"
              label="总毛利"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.shipProfit}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="perShipProfit"
              label="吨毛利"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.perShipProfit}}
              </template>
            </el-table-column>
          </el-table>
          <el-table :data="list1"  style="width: 100%;" class="data-table" :height="390" v-loading="listLoading1" v-if="cutIndex1 == 3">
            <el-table-column
              align="center"
              label="供应商等级"
              min-width="150">
              <template slot-scope="scope"><el-link @click="toPage('pSupplierSaleNumAnalysis')">{{scope.row.supplierLevel}}</el-link></template>
            </el-table-column>
            <el-table-column
              align="center"
              label="数量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.supplierCount}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="占比"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.supplierRate}}%
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="出库量"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.shipNum}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="总毛利"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.shipProfit}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="吨毛利"
              min-width="100">
              <template slot-scope="scope">
               {{scope.row.perShipProfit}}
              </template>
            </el-table-column>
          </el-table>
        </div>
    </div>

    <!--客户堆叠柱状图-->
    <div class="data-title" style="margin-top:10px" v-if="cutIndex2 != -1">
      <div class="title-left">
        <div class="title-item" :class="{'choose':cutIndex2 == 1}"  @click="changeTab2(1)" v-if="pClassOrderNumAnalysis">人员供应商分类统计</div>
        <div class="title-item" :class="{'choose':cutIndex2 == 2}"  @click="changeTab2(2)" v-if="pShipNumAnalysisBySupplierLevel">人员供应商等级统计</div>
      </div>
      <div class="title-right">
        <el-select @change="getBarData" size="mini" placeholder="请选择"  style="margin-right: 10px;width:100px" v-model="listQuery2.tab" >
          <el-option :key="1" value="shipNum" label="出库量"></el-option>
          <el-option :key="2" value="perShipProfit" label="吨毛利"></el-option>
          <el-option :key="3" value="shipProfit" label="总毛利"></el-option>
        </el-select>
        <el-select @change="getBarData" size="mini" placeholder="请选择毛利统计类型"  style="margin-right: 10px;width:120px" v-model="listQuery2.profitType" >
          <el-option :key="1" value="purchase" label="采购毛利统计"></el-option>
          <el-option :key="2" value="company" label="采销毛利统计"></el-option>
        </el-select>
        <el-date-picker
          @change="getBarData"
          style="width:210px;margin-right: 10px"
          size="mini"
          value-format="yyyy-MM-dd"
          v-model="listQuery2.date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
        <el-select @change="getBarData" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery2.goodsClass" >
          <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
        </el-select>
        <el-input size="mini" @change="getBarData" placeholder="请输入厂家" v-if="listQuery2.goodsClass" clearable style="width:150px;margin-right: 10px"  v-model="listQuery2.brandName"></el-input>
        <el-select @change="getBarData" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery2.kingGoodsId" filterable>
          <el-option
            v-for="item in goodsList"
            :key="item.kingId"
            :label="item.goodsSn"
            :value="item.kingId">
          </el-option>
        </el-select>
        <el-select size="mini" v-model="listQuery2.userIds"
                   style="width:140px"
                   collapse-tags
                   clearable @change="getBarData"  placeholder="请选择人员" multiple>
          <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="data-block" style="margin-top: 10px" v-if="cutIndex2 != -1">
      <div id="barChart" style="height: 350px" class="charts-div" v-loading="listLoading2"></div>
    </div>

    <!--客户跟进饼图-->
    <div class="data-title" style="margin-top: 10px">
      <div class="title-left">
        <div class="title-item choose" >供应商跟进</div>
      </div>
      <div class="title-right">
        <el-date-picker
          @change="getPieData2"
          style="width:150px;margin-right: 10px"
          size="mini"
          value-format="yyyy-MM"
          placeholder="请选择月份"
          v-model="listQuery3.month"
          type="month"
          align="right">
        </el-date-picker>
        <el-select size="mini" v-model="listQuery3.userIds"
                   style="width:140px"
                   collapse-tags
                   clearable @change="getPieData2"  placeholder="请选择人员" multiple>
          <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="order-block">
      <div class="data-block pie-block">
        <div class="pie-menu">
          <div class="pie-menu-item" :class="{'choose':cutIndex3 == 1}" @click="changeItem3(1)">跟进次数</div>
          <div class="pie-menu-item" :class="{'choose':cutIndex3 == 2}" @click="changeItem3(2)">跟进完成率</div>
          <div class="pie-menu-item" :class="{'choose':cutIndex3 == 3}" @click="changeItem3(3)">跟进类型</div>
        </div>
        <div id="pieChart2" class="charts-div" style="height:406px" v-if="cutIndex3 != 2"></div>
        <div style="height:406px; width:calc(100% - 120px);display: flex;justify-content: center;align-items: center" v-else>
          <el-progress type="circle" :percentage="allValidTrackingRate" :width="260" color="#69d1ad" :stroke-width="30"></el-progress>
        </div>

      </div>
      <div class="data-block order-table pie-table">
        <el-table :data="list3"  style="width: 100%;" class="data-table" :height="390" v-loading="listLoading1">
          <el-table-column
            align="center"
            label="姓名"
            min-width="100">
            <template slot-scope="scope">{{scope.row.userRealName}}</template>
          </el-table-column>
          <el-table-column
            align="center"
            label="供应商库总数"
            min-width="150">
            <template slot-scope="scope">
              {{scope.row.allSupplierNum}}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="应跟进供应商"
            min-width="150">
            <template slot-scope="scope">
              {{scope.row.supplierNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="应跟进次数"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.needTrackingNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="跟进完成率"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.trackingRate}}%
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="已跟进数"
            min-width="100">
            <template slot-scope="scope">
            {{scope.row.validTrackingNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="日常跟进"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.trackingDailyNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="拜访跟进"
            min-width="100">
            <template slot-scope="scope">
             {{scope.row.trackingVisitNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="成交跟进"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.trackingOrderNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="询价跟进"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.trackingInquiryNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="还需跟进"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.diffTrackingNum}}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!--客户跟进柱状图-->
    <div v-if="pUserTrackingAnalysis">
      <div class="data-title" style="margin-top: 10px">
        <div class="title-left">
          <div class="title-item choose" >人员供应商跟进情况</div>
        </div>
        <div class="title-right">
          <el-date-picker
            @change="getBarData2"
            style="width:150px;margin-right: 10px"
            size="mini"
            value-format="yyyy-MM"
            placeholder="请选择月份"
            v-model="listQuery4.month"
            type="month"
            align="right">
          </el-date-picker>
          <el-select size="mini" v-model="listQuery4.userIds"
                     style="width:140px"
                     collapse-tags
                     clearable @change="getBarData2"  placeholder="请选择人员" multiple>
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="data-block" style="margin-top: 10px">
        <div id="myChart" style="height: 300px" class="charts-div"></div>
      </div>
    </div>



  </div>
</template>

<script>
import {topSupplierList,numSummaryBySupplierType,numSummaryBySupplierLevel,shipAnalysisBySupplierType,shipAnalysisBySupplierLevel,puserTrackingAnalysis} from '@/api/data.js'
import echarts from "echarts";
import {formatDate} from '@/utils/date';
import store from '@/store';
import {mapGetters} from "vuex";
const defaultListQuery={
  "date" : [],
  "goodsClass" : "",//品类
  "brandName" : "", //厂家
  "tab" : "shipNum",
  userIds:[],
  kingGoodsId:'',
  profitType:'purchase'
};

const defaultListQuery2={
  "date" : [],
  "userIds" : [],
  "goodsClass" : "",//品类
  "brandName" : "", //厂家
  tab:'shipNum',
  kingGoodsId:'',
  profitType:'purchase'
};

const defaultListQuery3={
  "month" : "",   //统计月份
  userIds:[],
};

const defaultListQuery4={
  "userIds"   : [],   //人员ID
  "month" : "",   //统计月份
};

  export default {
    name: 'supplierData',
    data() {
      return {
        roles:store.getters.roles ? store.getters.roles : [],
        pickerOptions: {
          shortcuts: [{
            text: '今日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '本周',
            onClick(picker) {
              const now = new Date();
              // 获取今天是本周的第几天（0代表星期日，1代表星期一，...，6代表星期六）
              const dayOfWeek = now.getDay();
              // 计算本周第一天（星期一）的日期
              const startOfWeek = new Date(now);
              startOfWeek.setDate(now.getDate() - dayOfWeek + 1); // 调整为星期一
              // 计算本周最后一天（星期日）的日期
              const endOfWeek = new Date(startOfWeek);
              endOfWeek.setDate(startOfWeek.getDate() + 6); // 从星期一开始加6天得到星期日
              picker.$emit('pick', [startOfWeek, endOfWeek]);
            }
          }, {
            text: '本月',
            onClick(picker) {
              const now = new Date();
              // 获取当前月份和年份
              const month = now.getMonth();
              const year = now.getFullYear();
              // 计算本月第一天的日期
              const startOfMonth = new Date(year, month, 1);
              // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
              const startOfNextMonth = new Date(year, month + 1, 1);
              const endOfMonth = new Date(startOfNextMonth);
              endOfMonth.setDate(startOfNextMonth.getDate() - 1);
              picker.$emit('pick', [startOfMonth, endOfMonth]);
            }
          }, {
            text: '本年',
            onClick(picker) {
              const now = new Date();
              // 获取当前年份
              const year = now.getFullYear();
              // 计算本年第一天的日期（1月1日）
              const startOfYear = new Date(year, 0, 1);
              // 计算本年最后一天的日期（12月31日）
              const endOfYear = new Date(year, 11, 31);
              picker.$emit('pick', [startOfYear, endOfYear]);
            }
          }]
        },
        props:{multiple: true,label:'value',value:'label',emitPath:false},

        list1:[],
        listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
        listLoading1:false,
        cutIndex1:1,
        cutItme:'',
        pieChart:null,

        cutIndex2:1,
        barChart:null,
        listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
        listLoading2:false,
        radio:'1',


        listQuery3: JSON.parse(JSON.stringify(defaultListQuery3)),
        pieChart2:null,
        cutIndex3:1,
        listLoading3:false,
        allValidTrackingNum : 0,
        allDiffTrackingNum : 0,
        allValidTrackingRate : 0,
        allTrackingDailyNum : 0,
        allTrackingVisitNum : 0,
        allTrackingOrderNum : 0,
        allTrackingInquiryNum:0,
        list3:[],

        listQuery4: JSON.parse(JSON.stringify(defaultListQuery4)),
        myChart:null,



        resizeObserver:null

      }
    },
    props: {
      userList: {
        type: Array,
        default: () => []
      },
      classList:{
        type: Array,
        default: () => []
      },
      goodsList:{
        type: Array,
        default: () => []
      },
    },
    filters: {



    },
    created(){
      this.listQuery1.date = this.getMonth()
      this.listQuery2.date = this.getMonth()
      this.listQuery3.month = this.getMonth('month')
      this.listQuery4.month = this.getMonth('month')
      this.listQuery1.tab = 'shipNum'
      if(this.pClassOrderNumAnalysis){
        this.cutIndex2 = 1
      }else if(this.pShipNumAnalysisBySupplierLevel){
        this.cutIndex2 = 2
      }else{
        this.cutIndex2 = -1
      }
      this.$nextTick(()=>{
        this.getPieData()
        if(this.cutIndex2 != -1){
          this.getBarData()
        }
        this.getPieData2()
        if(this.pUserTrackingAnalysis){
          this.getBarData2()
        }
        // 智能响应式方案
        const elements = document.querySelectorAll('.charts-div');
        this.resizeObserver = new ResizeObserver(entries => {
          entries.forEach(entry => {
            if(entry.target.id == 'pieChart'){
              this.pieChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'barChart'){
              this.barChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'pieChart2'){
              this.pieChart2.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'myChart'){
              this.myChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }
          })
        });
        elements.forEach(el => {
          this.resizeObserver.observe(el);
        });
      })

    },

    beforeDestroy() {
      if (this.resizeObserver) {
        const elements = document.querySelectorAll('.charts-div');
        elements.forEach(el => {
          this.resizeObserver.unobserve(el);
        });
        this.resizeObserver.disconnect();
        this.pieChart.dispose();
        if(this.barChart){
          this.barChart.dispose()
        }
        this.pieChart2.dispose();
        if(this.myChart){
          this.myChart.dispose();
        }

      }
    },
    components:{

    },
    computed:{
      pClassOrderNumAnalysis() {
        if(this.roles.indexOf("pClassOrderNumAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      pShipNumAnalysisBySupplierLevel() {
        if(this.roles.indexOf("pShipNumAnalysisBySupplierLevel") != -1){
          return true
        }else{
          return false
        }
      },

      pUserTrackingAnalysis() {
        if(this.roles.indexOf("pUserTrackingAnalysis") != -1){
          return true
        }else{
          return false
        }
      },


    },
    methods: {
      toPage(type){
        let routeData
        switch (type) {
          case 'pSupplierSaleNumAnalysis':
            routeData = this.$router.resolve({name:'pSupplierSaleNumAnalysis',query:{dataDate:this.listQuery1.date,dataGoodsClass:this.listQuery1.goodsClass,dataBrandName:this.listQuery1.brandName,dataKingGoodsId:this.listQuery1.kingGoodsId,dataUserIds:this.listQuery1.userIds.join(',')}});
            break;
          case 'supplierFollowUpReport':
            routeData = this.$router.resolve({name:'supplierFollowUpReport',query:{dataMonth:this.listQuery4.month}});
            break;
          case 'pSupplierSaleNumAnalysis2':
            routeData = this.$router.resolve({name:'pSupplierSaleNumAnalysis',query:{dataDate:this.listQuery2.date,dataGoodsClass:this.listQuery2.goodsClass,dataBrandName:this.listQuery2.brandName,dataKingGoodsId:this.listQuery2.kingGoodsId,dataUserIds:this.listQuery2.userIds.join(',')}});
            break;
        }
        window.open(routeData.href);
      },
      changeItem1(tab){
        this.listQuery1.tab = tab;
        this.getPieData()
      },
      //获取本月时间
      getMonth(type){
        const now = new Date();
        // 获取当前月份和年份
        const month = now.getMonth();
        const year = now.getFullYear();
        // 计算本月第一天的日期
        const startOfMonth = new Date(year, month, 1);
        // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
        const startOfNextMonth = new Date(year, month + 1, 1);
        const endOfMonth = new Date(startOfNextMonth);
        endOfMonth.setDate(startOfNextMonth.getDate() - 1);
        if(type){
          return formatDate(new Date(startOfMonth), 'yyyy-MM')
        }
        return [formatDate(new Date(startOfMonth), 'yyyy-MM-dd'),formatDate(new Date(endOfMonth), 'yyyy-MM-dd')]
      },
      changeTab1(index){
        this.cutIndex1 = index
        this.listQuery1 = JSON.parse(JSON.stringify(defaultListQuery))
        this.listQuery1.date = this.getMonth()
        this.listQuery1.tab = 'shipNum'
        this.getPieData()
      },
      getPieData(){
        let fn
        this.listQuery1.brandName = this.listQuery1.goodsClass ? this.listQuery1.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
        listQuery.userIds = listQuery.userIds.join(',')
        if(this.cutIndex1 == 1){
          fn = topSupplierList
        }else if(this.cutIndex1 == 2){
          fn = numSummaryBySupplierType
        }else if(this.cutIndex1 == 3){
          fn = numSummaryBySupplierLevel
        }
        this.listLoading1 = true;
        fn(listQuery).then((res)=>{
          this.list1 = res
          this.listLoading1 = false
          this.drawPie(this.list1)
        })

      },
      drawPie(res){
        this.pieChart = echarts.init(document.getElementById('pieChart'),null,{renderer: 'canvas',useDirtyRect: false});
        let data = []
        let colorList = ['#4e75ec','#ffbb70','#91cc75','#ee6666','#73c0de','#3ba272','#fc8452','#9a60b4','#ea7ccc','#b8c85f']
        let name = ''
        if(this.cutIndex1 == 1){
          name =  'supplierName'
        }else if(this.cutIndex1 == 2){
          name =  'supplierType'
        }else if(this.cutIndex1 == 3){
          name =  'supplierLevel'
        }
        let value = this.listQuery1.tab
        res.forEach((el,index)=>{
          if(el[value] > 0){
            data.push({
              name:el[name],
              value:el[value],
              itemStyle:{color:colorList[index]}
            })
          }
        })
        let roseType = this.cutIndex1 == 1 ? 'area':''
        let radius = this.cutIndex1 == 1 ? [20, '70%']:['40%', '60%']
        let option = {
          series: [
            {
              type: 'pie',
              label: {
                normal: {
                  show: true,
                  alignTo: 'edge',
                  minMargin: 5,
                  edgeDistance: 10,
                  lineHeight: 15,
                  align: 'right', // 标签文本对齐方式
                  formatter: function(params) {
                    var name = params.name;
                    var maxLabelLength = 6; // 可根据需要调整
                    // 如果标签文本长度超过最大显示长度，则截断并添加省略号
                    if (name.length > maxLabelLength) {
                      name = name.substring(0, maxLabelLength) + '\n'+name.substring(maxLabelLength, name.length);
                    }
                    return `{num|${params.value}}\n{name|${name}}`
                  }, // 显示数据项名称、值
                  rich: {
                    num: {
                      fontSize: 12,
                      fontWeight:'bold',
                      color: '#5b5b5b'
                    },
                    name: {
                      fontSize: 9,
                      color: '#999'
                    },
                  }
                }
              },
              radius: radius,
              center: ['50%', '50%'],
              roseType: roseType,
              labelLine: {
                normal: {
                  show: true,
                  length: 10,
                  length2: 15,
                  maxSurfaceAngle: 80
                }
              },
              itemStyle: {
                // 这里的颜色会应用到所有的扇区上，如果想要为每个扇区指定不同的颜色，需要使用 data 中的 itemStyle
                borderRadius: 10, // 统一设置圆角半径（但这种方式可能不被所有版本支持，具体看ECharts文档）
                borderColor: '#fff', // 设置扇区边框颜色
                borderWidth: 1 // 设置扇区边框宽度
              },
              data: data
            }
          ]
        };
        this.pieChart.setOption(option);

        this.pieChart.on('click', (params)=> {
          this.toPage('pSupplierSaleNumAnalysis')
        })

      },
      changeTab2(index){
        this.cutIndex2 = index
        this.listQuery2 = JSON.parse(JSON.stringify(defaultListQuery2))
        this.listQuery2.date = this.getMonth()
        this.listQuery2.tab = 'shipNum'
        this.barChart.clear()
        this.getBarData()
      },

      getBarData(){
        let fn
        this.listQuery2.brandName = this.listQuery2.goodsClass ? this.listQuery2.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery2));
        listQuery.userIds = listQuery.userIds.join(',')
        if(this.cutIndex2 == 1){
          fn = shipAnalysisBySupplierType
        }else if(this.cutIndex2 == 2){
          fn = shipAnalysisBySupplierLevel
        }
        this.listLoading2 = true;
        fn(listQuery).then((res)=>{
          this.listLoading2 = false
          this.drawBar(res)
        })
      },
      drawBar(oldData){
        this.barChart = echarts.init(document.getElementById('barChart'),null,{renderer: 'canvas',useDirtyRect: false});
        let unit = this.listQuery2.tab == 'shipNum'  ? '吨' : '元'
        let self  = this
         let categories = oldData.data.map(item => item.userRealName)
         let colorList = ['#4e75ec','#ffbb70','#91cc75','#ee6666','#73c0de','#3ba272','#fc8452','#9a60b4','#ea7ccc','#b8c85f']
         let series = []
         let legend = oldData.series.map(item => item.label)

         let dataList = {}
         oldData.series.forEach((el,index)=>{
           dataList[el.key] = []
           oldData.data.forEach((ee)=>{
             dataList[el.key].push(Number(ee[el.key]))
           })
           series.push({
             name:el.label,
             data:dataList[el.key],
             barWidth:16,
             barGap: '10%', // 不同系列间的柱子间隔
             barCategoryGap: '10%', // 同一系列内柱子间隔
             type: 'bar',
             stack: 'total',
             yAxisIndex: 0,
             itemStyle: {
               color: colorList[index]
             },
           })

        })

        const minShowItems = 15; // 触发滚动的最小数据量

        let option = {

          tooltip: {
            trigger: 'axis',
            backgroundColor:'none',
            formatter: function(params) {
              let con = ''
              for(let i=0;i<params.length;i++){
                let condiv = `<div style="color:#8b8b8b;font-size: 14px;">${params[i].seriesName}：<span style="color:${colorList[i]};font-weight: bold">${params[i].value}</span>${params[i].seriesName.indexOf('次数') != -1 ? '次' : unit}</div>`
                con = con+condiv
              }
              let html = ''
              html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  ${con}
                  </div>`;
              return html;
            }
          },
          legend: {
            data: legend,
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
            y: 40,           // 垂直起点50px
          },
          grid: {
            left: 50,          // 左侧留空比例
            right: 30,          // 右侧留空
            bottom:30,
            top:80,
            containLabel: true,   // 确保标签不被截断
          },
          dataZoom: [
            {
              type: 'slider',      // 滑动条型dataZoom（必须声明）
              height: 10,           // 滚动条高度
              bottom:16,
              show: oldData.data.length > minShowItems,          // 默认显示
              xAxisIndex: 0,       // 控制第一个xAxis
              zoomLock: true,        // 禁止缩放（仅滚动）
              start: 0,
              end: Math.min(100, (minShowItems / oldData.data.length) * 100), // 动态计算初始窗口
            }
          ],
          xAxis: {
            type: 'category',
            data: categories,
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 14,        // 字体大小
            },
            axisTick: {
              show: false,          // 显示刻度线
            },
          },
          yAxis: [{
            type: 'value',
            nameTextStyle:{
              color:'#898989'
            },
            position: 'left',
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 10,        // 字体大小
            },
            splitLine: {
              show: true,                    // 需手动开启
              lineStyle: {
                color: '#ebebeb',  // 半透明细线
                width: 0.5
              }
            }
          }
          ],
          series: series
        };

        this.barChart.setOption(option);
        this.barChart.on('click', (params)=> {
            this.toPage('pSupplierSaleNumAnalysis2')
        })
      },

      changeItem3(index){
        this.cutIndex3 = index
        if(this.cutIndex3 == 2){
          this.pieChart2.dispose();
        }else{
          this.$nextTick(()=>{
            this.drawPie2(this.allValidTrackingNum,this.allDiffTrackingNum,this.allTrackingDailyNum,this.allTrackingVisitNum,this.allTrackingOrderNum,this.allTrackingInquiryNum)
          })
        }

      },
      getPieData2(){
        let listQuery = JSON.parse(JSON.stringify(this.listQuery3));
        listQuery.userIds = listQuery.userIds.join(',')
        this.listLoading3 = true
        puserTrackingAnalysis(listQuery).then((res)=>{
          this.listLoading3 = false
          this.list3 = res.list
          this.allValidTrackingNum = res.allValidTrackingNum
          this.allDiffTrackingNum = res.allDiffTrackingNum
          this.allValidTrackingRate = res.allValidTrackingRate
          this.allTrackingDailyNum = res.allTrackingDailyNum
          this.allTrackingVisitNum = res.allTrackingVisitNum
          this.allTrackingOrderNum = res.allTrackingOrderNum
          this.allTrackingInquiryNum = res.allTrackingInquiryNum
          this.drawPie2(this.allValidTrackingNum,this.allDiffTrackingNum,this.allTrackingDailyNum,this.allTrackingVisitNum,this.allTrackingOrderNum,this.allTrackingInquiryNum)
        })

      },
      drawPie2(allValidTrackingNum,allDiffTrackingNum,allTrackingDailyNum,allTrackingVisitNum,allTrackingOrderNum,allTrackingInquiryNum){
        this.pieChart2 = echarts.init(document.getElementById('pieChart2'),null,{renderer: 'canvas',useDirtyRect: false});
        let res = []
        if(this.cutIndex3 == 1){
          res.push(
            { value: allDiffTrackingNum, name: '需跟进数' },
            { value: allValidTrackingNum, name: '已跟进数' }
          )
        }else if(this.cutIndex3 == 3){
          res.push(
            { value: allTrackingDailyNum, name: '日常跟进次数' },
            { value: allTrackingVisitNum, name: '拜访跟进次数' },
            { value: allTrackingOrderNum, name: '成交跟进次数' },
            {value:allTrackingInquiryNum,name:'询价跟进次数'}
          )
        }

        let data = []
        let colorList = ['#4e75ec','#ffbb70','#91cc75','#ee6666','#73c0de','#3ba272','#fc8452','#9a60b4','#ea7ccc','#b8c85f']
        let name = 'name'
        let value = 'value'
        res.forEach((el,index)=>{
          // console.log("el",el)
          data.push({
            name:el[name],
            value:el[value],
            itemStyle:{color:colorList[index]}
          })
        })
        let option = {
          legend: {
            bottom: 10,
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
          },
          series: [
            {
              type: 'pie',
              label: {
                normal: {
                  formatter: '{c}', // 显示数据项名称、值和百分比
                  textStyle: {
                    color: '#5b5b5b', // 设置标识字体颜色
                    fontWeight: 'bold'
                  },
                  fontSize:14,
                }
              },
              radius: ['40%', '60%'],
              labelLine: {
                normal: {
                  show: true,
                  length: 20, // 第一段长度
                  length1: 20, // 第一段长度
                }
              },
              itemStyle: {
                // 这里的颜色会应用到所有的扇区上，如果想要为每个扇区指定不同的颜色，需要使用 data 中的 itemStyle
                borderRadius: 10, // 统一设置圆角半径（但这种方式可能不被所有版本支持，具体看ECharts文档）
                borderColor: '#fff', // 设置扇区边框颜色
                borderWidth: 1 // 设置扇区边框宽度
              },
              data: data
            }
          ]
        };
        this.pieChart2.setOption(option);
      },

      getBarData2(){
        let listQuery = JSON.parse(JSON.stringify(this.listQuery4));
        listQuery.userIds = listQuery.userIds.join(',')
        puserTrackingAnalysis(listQuery).then((res)=>{
          this.drawCharts(res.list)
        })

      },
      drawCharts(data){
        this.myChart = echarts.init(document.getElementById('myChart'),null,{renderer: 'canvas',useDirtyRect: false});
        // 假设我们有目标销量和实际销量的数据
        let salesData = data

        // 准备数据
        let categories = salesData.map(item => item['userRealName']);  //x轴
        let targetSales = salesData.map(item => item['needTrackingNum']);//目标数量
        let actualSales = salesData.map(item => item['validTrackingNum']);//实际数量
        let differences = salesData.map(item => Number((item['validTrackingNum'] - item['needTrackingNum']).toFixed(3))*1);//差异值
        let completion = salesData.map(item => item['trackingRate']); //完成率

        // 确定每个项目哪个销量更高
        let isActualHigher = salesData.map(item => item['validTrackingNum'] >= item['needTrackingNum']);  //是否超过目标

        let higherSalesIndexes = [];
        let lowerSalesValues = [];
        let lineColors = [];
        targetSales.forEach((target, index) => {
          let diff = actualSales[index] - target;
          lineColors.push(diff > 0 ? 'green' : 'red');
          if (actualSales[index] > target) {
            higherSalesIndexes.push(index);
            lowerSalesValues.push(target);
          } else {
            higherSalesIndexes.push(-1); // 标记为无对应高销量
            lowerSalesValues.push(actualSales[index]);
          }
        });
        const minShowItems = 15; // 触发滚动的最小数据量
        let yName,y1Name,y2Name,lineName
        yName = '需跟进'
        y1Name = '已跟进'
        y2Name = '未跟进'
        lineName = '跟进次数'

        let option = {
          tooltip: {
            trigger: 'axis',
            backgroundColor:'none',
            formatter: function(params) {
              let diff = Number((params[1].value-params[0].value).toFixed(3))*1
              let color = '#000000'
              if(params[1].value-params[0].value >= 0){
                diff = '↑ '+Math.abs(diff)+'次'
                color = 'green'
              }else{
                color = 'red'
                diff = '↓ '+Math.abs(diff)+'次'
              }
              let html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  <div style="color:#8b8b8b;font-size: 14px;">${yName}：<span style="color:#6084f2;font-weight: bold">${params[0].value}次</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">${y1Name}：<span style="color:#ffc27b;font-weight: bold">${params[1].value}次</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">${y2Name}：<span style="color:${color};font-weight: bold">${diff}</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">完成率：<span style="color:#ef915d;font-weight: bold">${params[2].value}%</span></div>
                  </div>`;
              return html;
            }
          },
          legend: {
            data: [yName, y1Name,'完成率'],
            orient: 'horizontal',
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
            x: '50%',        // 水平起点为容器宽度的15%
            y: 20,           // 垂直起点50px
          },
          grid: {
            left: 50,          // 左侧留空比例
            right: 30,          // 右侧留空
            bottom:30,
            top:80,
            containLabel: true,   // 确保标签不被截断
          },
          dataZoom: [
            {
              type: 'slider',      // 滑动条型dataZoom（必须声明）
              height: 10,           // 滚动条高度
              bottom:16,
              show: salesData.length > minShowItems,          // 默认显示
              xAxisIndex: 0,       // 控制第一个xAxis
              zoomLock: true,        // 禁止缩放（仅滚动）
              start: 0,
              end: Math.min(100, (minShowItems / salesData.length) * 100), // 动态计算初始窗口
            }
          ],
          xAxis: {
            type: 'category',
            data: categories,
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 14,        // 字体大小
            },
            axisTick: {
              show: false,          // 显示刻度线
            },
          },
          yAxis: [
            {
              type: 'value',
              name: lineName,
              nameTextStyle:{
                color:'#898989'
              },
              position: 'left',
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 10,        // 字体大小
              },
              splitLine: {
                show: true,                    // 需手动开启
                lineStyle: {
                  color: '#ebebeb',  // 半透明细线
                  width: 0.5
                }
              }
            },
            {
              type: 'value',
              name: '完成率',
              nameTextStyle:{
                color:'#898989'
              },
              position: 'right',
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 10,        // 字体大小
              },
              splitLine: {
                show: false,                    // 需手动开启
              }
            },
          ],
          series: [
            {
              name:yName,
              type: 'bar',
              data: targetSales,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#6084f2' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
              label: {
                show: true,
                position: 'top',
                color:'red',
                fontSize:14,
                offset: [20, 0] ,
                formatter: function(params) {
                  let diff = differences[params.dataIndex];
                  // 实际比目标小
                  if (!isActualHigher[params.dataIndex]) {
                    return '↓ '+Math.abs(diff)+'次';
                  }
                  return '';
                }
              }
            },
            {
              name: y1Name,
              type: 'bar',
              data: actualSales,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#ffc27b' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
              label: {
                show: true,
                position: 'top',
                color:'green',
                fontSize:14,
                offset: [-14, 0] ,
                formatter: function(params) {
                  let diff = differences[params.dataIndex];
                  // 实际比目标大
                  if (isActualHigher[params.dataIndex]) {
                    return '↑ '+Math.abs(diff)+'次';
                  }
                  return '';
                }
              }
            },
            {
              name: '完成率',
              type: 'line',
              data: completion,
              yAxisIndex: 1,
              lineStyle: {
                color: '#ee905c',
                width: 2,
              },
              symbol: 'emptyCircle',       // 顶点形状（circle/diamond/triangle等）
              symbolSize: 8,         // 顶点大小
              itemStyle: {
                color: '#ee905c',     // 顶点填充色
                borderColor: '#ee905c',  // 顶点边框色
                borderWidth: 1        // 边框粗细
              }
            },
            {
              name: '连接线',
              type: 'custom',
              renderItem: function(params, api) {
                let categoryIndex = params.dataIndex;
                let startPoint = api.coord([categoryIndex, lowerSalesValues[categoryIndex]]);
                let endPoint = api.coord([categoryIndex, Math.max(targetSales[categoryIndex], actualSales[categoryIndex])]);
                let x1,x2
                if(isActualHigher[categoryIndex] ){
                  x1 = startPoint[0]-10
                  x2 = endPoint[0]-10
                }else{
                  x1 = startPoint[0]+10
                  x2 = endPoint[0]+10
                }

                return {
                  type: 'line',
                  shape: {
                    x1: x1,
                    y1: startPoint[1],
                    x2: x2,
                    y2: endPoint[1]
                  },
                  style: api.style({
                    stroke: lineColors[categoryIndex],
                    lineWidth:1
                  })
                };

              },
              data: higherSalesIndexes.map((index, i) => [i]) // 使用项目的索引作为数据
            },
            {
              name: '连接线3',
              type: 'custom',
              renderItem: function(params, api) {
                let categoryIndex = params.dataIndex;
                let startPoint = api.coord([categoryIndex, lowerSalesValues[categoryIndex]]);
                let endPoint = api.coord([categoryIndex, Math.max(targetSales[categoryIndex], actualSales[categoryIndex])]);
                let x1,x2
                if(isActualHigher[categoryIndex] ){
                  x1 = endPoint[0]+2
                  x2 = endPoint[0]-20
                }else{
                  x1 = endPoint[0]-2
                  x2 = endPoint[0]+20
                }

                return {
                  type: 'line',
                  shape: {
                    x1: x1,
                    y1: endPoint[1],
                    x2: x2,
                    y2: endPoint[1]
                  },
                  style: api.style({
                    stroke: '#888888',
                    lineWidth:1
                  })
                };

              },
              data: higherSalesIndexes.map((index, i) => [i]) // 使用项目的索引作为数据
            }
          ]
        };
        this.myChart.setOption(option);
        this.myChart.on('click', (params)=> {
          this.toPage('supplierFollowUpReport')
        })
      },

    }
  }
</script>


